﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DingHeng.TransportationManagement.Entity.Constant;
using DingHeng.TransportationManagement.DataAccess;
using DingHeng.TransportationManagement.Entity;

namespace DingHeng.TransportationManagement.Business
{
    public class VehicleDispatchFormBiz
    {
        public TransportationLog GenerateTransportationForm(Guid vehicleDispatchId, User currentUser)
        {

            using (VehicleDispatchFormDataAccess vdfa = new VehicleDispatchFormDataAccess())
            {
                VehicleDispatchForm vehicleDispatchForm = vdfa.LoadByCondition(v => v.ID == vehicleDispatchId && v.IsActive==true).FirstOrDefault();
                if (vehicleDispatchForm != null)
                {
                    TransportationLog transportationLog = new TransportationLog();
                    vehicleDispatchForm.UpdateBy =
                        transportationLog.UpdateBy =
                        transportationLog.CreateBy = currentUser.Name;

                    vehicleDispatchForm.UpdateDate =
                        transportationLog.UpdateDate =
                        transportationLog.CreateDate = DateTime.Now;

                    transportationLog.ID = Guid.NewGuid();
                    transportationLog.OperationShiftDate = currentUser.ShiftDate;
                    transportationLog.OperationShiftTypeID = Guid.Parse(currentUser.ShiftType);
                    transportationLog.VehicleDispatchID = vehicleDispatchForm.ID;
                    
                    //transportationLog.LoadTime = vehicleDispatchForm.UpdateDate;
                    

                    vehicleDispatchForm.TransportationLogs.Add(transportationLog);

                    //vehicleDispatchForm.Status = Guid.Parse(StringConstant.StatusLoaded);

                    vdfa.SaveChanges();

                    return transportationLog;
                }
                return null;
            }

        }
        public TransportationForm GenerateTransportationForm(Guid vehicleDispatchId, string currentUser)
        {

            using (VehicleDispatchFormDataAccess vdfa = new VehicleDispatchFormDataAccess())
            {
                VehicleDispatchForm vehicleDispatchForm = vdfa.LoadByCondition(v => v.ID == vehicleDispatchId).FirstOrDefault();
                if (vehicleDispatchForm != null
                    && vehicleDispatchForm.Status.HasValue
                    && vehicleDispatchForm.Status.Value == Guid.Parse(StringConstant.StatusDispatched))
                {
                    TransportationForm transportationForm = new TransportationForm();
                    vehicleDispatchForm.UpdateBy =
                        transportationForm.UpdateBy =
                        transportationForm.CreateBy = currentUser;

                    vehicleDispatchForm.UpdateDate =
                        transportationForm.UpdateDate =
                        transportationForm.CreateDate = DateTime.Now;

                    transportationForm.ID = Guid.NewGuid();
                    transportationForm.IsActive = true;
                    transportationForm.Status = Guid.Parse(StringConstant.StatusLoaded);
                    transportationForm.VehicleDispatchID = vehicleDispatchForm.ID;
                    transportationForm.VehicleID = vehicleDispatchForm.VehicleID;
                    transportationForm.LoadTime = vehicleDispatchForm.UpdateDate;
                    DateTime shiftDate;
                    //transportationForm.LoadShiftType =
                    //    Guid.Parse(new Common().ShiftTypeCalculate(DateTime.Now, out shiftDate));
                    //transportationForm.LoadShiftDate = shiftDate;

                    vehicleDispatchForm.TransportationForms.Add(transportationForm);
                    vehicleDispatchForm.Status = Guid.Parse(StringConstant.StatusLoaded);

                    vdfa.SaveChanges();

                    return transportationForm;
                }
                return null;
            }

        }
        public VehicleDispatchForm LoadById(Guid id)
        {
            using (VehicleDispatchFormDataAccess vdfa = new VehicleDispatchFormDataAccess())
            {
                return vdfa.LoadByCondition(v => v.ID == id).FirstOrDefault();
            }
        }
        public VehicleDispatchFormInfo LoadByInfoID(Guid id)
        {
            using (VehicleDispatchFormInfoDataAccess vida = new VehicleDispatchFormInfoDataAccess())
            {
                return vida.LoadByCondition(v => v.ID == id).FirstOrDefault();
            }
        }
        public int Save(VehicleDispatchForm entity)
        {
            if (entity.ID == Guid.Empty || entity.ID == null)
            {
                entity.Code = generateCode();
                entity.ID = Guid.NewGuid();
            }
            using (VehicleDispatchFormDataAccess vdfa = new VehicleDispatchFormDataAccess())
            {
                return vdfa.Save(entity);
            }
        }
        private string generateCode()
        {
            string lastCode = string.Empty;
            using (VehicleDispatchFormDataAccess vda = new VehicleDispatchFormDataAccess())
            {
                DateTime? maxTime = vda.LoadAll().Max(v => v.CreateDate);
                if (maxTime.HasValue)
                {
                    lastCode = vda.LoadByCondition(v => v.CreateDate == maxTime).FirstOrDefault().Code;
                    int codeCount = int.Parse(lastCode.Substring(8, 8));
                    codeCount++;

                    Match numberMatch = Regex.Match(string.Format("00000000{0}", codeCount), DingHeng.TransportationManagement.Business.Constant.StringConstant.GeneratRegex);
                    if (numberMatch.Success)
                    {
                        return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMdd"), numberMatch.Groups["number"].Value);
                    }
                    else
                    {
                        throw new Exception("Generate number exception");
                    }
                }
                else
                {
                    return string.Format("{0}00000001", DateTime.Now.ToString("yyyyMMdd"));
                }
            }

        }
        public bool Verify(VehicleDispatchForm entity)
        {
            //TODO:根据业务逻辑编写校验规则
            return true;
        }
        public void Print(Guid vehicleDispatchId, string currentUser)
        {
            using (VehicleDispatchFormDataAccess vdfa = new VehicleDispatchFormDataAccess())
            {
                VehicleDispatchForm vehicleDispatchForm = vdfa.LoadByCondition(v => v.ID == vehicleDispatchId).FirstOrDefault();
                if (vehicleDispatchForm != null
                    && vehicleDispatchForm.Status.HasValue
                    && vehicleDispatchForm.Status.Value == Guid.Parse(StringConstant.StatusCheckIn))
                {
                    vehicleDispatchForm.UpdateDate = DateTime.Now;
                    vehicleDispatchForm.UpdateBy = currentUser;
                    vehicleDispatchForm.Status = Guid.Parse(StringConstant.StatusDispatched);
                    vdfa.SaveChanges();
                }
            }
        }
        public List<VehicleDispatchFormInfo> GetPageList(VehicleDispatchFormCriteria criteria, Pager<VehicleDispatchFormInfo> pager)
        {
            using (VehicleDispatchFormInfoDataAccess access = new VehicleDispatchFormInfoDataAccess())
            {
                IQueryable<VehicleDispatchFormInfo> query = access.LoadByCondition(v => v.IsActive == true);
                if (!string.IsNullOrEmpty(criteria.Code))
                {
                    query = query.Where(v => v.Code.Contains(criteria.Code));
                }
                if (criteria.DispatchTimeEnd.HasValue)
                {
                    query = query.Where(v => v.DispatchTime <= criteria.DispatchTimeEnd);
                }
                if (criteria.DispatchTimeStart.HasValue)
                {
                    query = query.Where(v => v.DispatchTime >= criteria.DispatchTimeStart);
                }
                if (!string.IsNullOrEmpty(criteria.VehicleNo))
                {
                    query = query.Where(v => v.VehicleCode.Contains(criteria.VehicleNo));
                }
                if (!string.IsNullOrEmpty(criteria.VehicleLicensePlateNo))
                {
                    query = query.Where(v => v.LicensePlateNo.Contains(criteria.VehicleLicensePlateNo));

                }

                return access.GetPageList(query, pager);
            }
        }
    }
}
